<style>
    .edit .ant-form-item-control{
        line-height: 100%;
    }
</style>
<template>
    <div class="page-container is-form">
        <a-spin :spinning="spinning">
            <a-form :layout="formLayout" :form="form">
                <a-form-item label='条形码'  v-bind="formItemLayout">
                    <a-input-search  placeholder='请输入条形码'
                                    @search="onCreateBarCode"  style="width: 300px;"
                                    v-decorator="['barCode',{rules: [{ required: true, message: '条形码不能为空!' }]}]">
                        <a-button type="primary"  slot="enterButton">生成</a-button>
                    </a-input-search>
                </a-form-item>
                <a-form-item label='规格名称'  v-bind="formItemLayout">
                    <a-input placeholder='请输入规格名称' v-decorator="['name',{rules: [{ required: true, message: '规格名称不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>

                <a-form-item label='规格主图' v-bind="formItemLayout" help="建议图片 JPG、PNG、GIF格式，小于500k">
                    <a-upload  listType="picture-card"
                               :fileList="fileList"  @preview="handlePreview"
                               :action="uploadAction"  @change="handleChange">
                        <div v-if="fileList.length < 1">
                            <a-icon type="plus" />
                            <div class="ant-upload-text">上传</div>
                        </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                        <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                    <a-input type="hidden" v-decorator="['mainImage',{rules: [{ required: true, message: '请上传规格主图!' }]}]" />
                </a-form-item>
                <a-form-item label='价格'  v-bind="formItemLayout">
                    <a-input placeholder='请输入价格' v-decorator="['price',{rules: [{ required: true, message: '价格不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>
                <a-form-item label='进价'  v-bind="formItemLayout">
                    <a-input placeholder='请输入价格' v-decorator="['purchasePrice',{rules: [{ required: true, message: '进价不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>
                <a-form-item label='库存'  v-bind="formItemLayout">
                    <a-input placeholder='请输入库存' v-decorator="['stock',{rules: [{ required: true, message: '库存不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>
                <a-form-item label='排序'  v-bind="formItemLayout">
                    <a-input placeholder='请输入库存' v-decorator="['sort',{rules: [{ required: true, message: '库存不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>
                <a-form-item :wrapperCol="{span:8,offset:4}">
                    <a-input type="hidden" v-decorator="['id']" />
                    <a-button type='primary'  :loading="bntLoading" @click="onSubmit">保 存</a-button>
                </a-form-item>
            </a-form>
        </a-spin>
    </div>
</template>
<script>
    import {save,findDetail} from "../../api/goodsSpec";
    import { mapGetters } from 'vuex'
    export default {
        beforeCreate(){
            this.form = this.$form.createForm(this);
        },
        data() {
            return{
                formLayout:'horizontal',
                spinning:false,
                params:{
                    id:0,
                    goodsId:0
                },
                loading:false,
                bntLoading:false,
                uploadAction:this.UPLOAD_URL,
                mainImage:'',
                fileList: [],
                previewVisible: false,
                previewImage: '',
            }
        },
        computed: {
            formItemLayout () {
                const { formLayout } = this
                return formLayout === 'horizontal' ? {
                    labelCol: { span:4},
                    wrapperCol: { span:18 },
                } : {}
            },
            ...mapGetters([
                'companyId'
            ]),
        },
        methods:{
            handleCancel() {
                this.previewVisible = false
            },
            handlePreview(file) {
                this.previewImage = file.url || file.thumbUrl
                this.previewVisible = true
            },
            handleChange({file, fileList}) {
                this.loading = true
                if(file.status == 'removed') this.form.setFieldsValue({'mainImage':''});
                if(file.status == 'uploading') {
                    const isJPG = file.type === 'image/jpeg';
                    const isPNG = file.type === 'image/png';
                    const isGif = file.type === 'image/gif';
                    if (!isJPG && !isPNG && !isGif) {
                        this.$message.error('图片格式错误,请检查后重新上传!');
                        this.loading = false;
                        return;
                    }
                    const isLt500KB = file.size / 1024 / 500
                    if (!isLt500KB) {
                        this.$message.error('图片大小不合适,请上传小于500KB的图片!');
                        this.loading = false;
                        return;
                    }
                }
                this.fileList = fileList;
                // 根据服务端返回数据筛选上传成功的文件
                fileList.forEach((file) => {
                    if (file.response) {
                        this.form.setFieldsValue({'mainImage': file.response.data});
                    }
                });
                this.loading = false;
            },
            onCreateBarCode(){
                var str = new Date().getTime().toString();
                var s = str.substr(str.length-4,str.length-1);
                var companyId  = this.companyId+"";

                if(this.companyId<10){
                    companyId = "0"+companyId;
                }else{
                    companyId = companyId.substr(companyId.length-2,companyId.length)
                }
                var seconds = new Date().getSeconds();
                if(seconds<10) seconds = "0"+seconds;
                var date = new Date().getDate();
                if(date < 10) date = "0"+date;
                var barCode = "H"+companyId+seconds+"18"+s+date;
                this.form.setFieldsValue({'barCode':barCode});
            },
            onSubmit(){
                this.bntLoading = true;
                this.form.validateFields(
                    (err,values) => {
                        if (!err) {
                            this.onSave(values);
                        }else{
                            this.bntLoading = false;
                        }
                    },
                )
            },
            async onSave(data){
                this.spinning = true;
                let resp = await save(data);
                this.spinning = false;
                let _this = this;
                if(this.qUtil.validResp(resp)){
                    this.$success({title:'保存成功!',okText:'确定',
                        onOk(){_this.$router.push({name:'GoodsSpecList',query:{goodsId:_this.params.goodsId}});}
                    });
                }else{
                    this.$error({title:resp.msg,okText:'确定'});
                    this.bntLoading = false;
                }
            },
            async onLoad(){
                if(this.params.id == 0) return false;
                let resp = await findDetail(this.params.id);
                if(this.qUtil.validResp(resp)){
                    const {id,barCode,name,mainImage,price,purchasePrice,stock,sort} = resp.data.goodsSpec;
                    this.form.setFieldsValue({id,barCode,name,mainImage,price,purchasePrice,stock,sort});
                    if (resp.data.goodsSpec.mainImage) {
                        this.fileList.push({
                            uid: '-1',
                            name: ' ',
                            status: 'done',
                            url: resp.data.goodsSpec.mainImage
                        })
                    }
                }
            }
        },
        mounted(){
            this.params.id = this.$route.query.id || 0;
            this.params.goodsId = this.$route.query.goodsId;
            this.onLoad();
        },
    }
</script>